<template>
       <!--      添加考试弹窗-->
       <el-drawer size="650px" :with-header="false" :append-to-body="true" :visible.sync="addExamDrawer">
        <exam-item-add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @addExamSure="addExamSure">  </exam-item-add-or-update>
        <div class="right-container">
          <div class="container-header">
            <div style="font-size: 14px">考试设置</div>
            <div @click="handleAddExamClose">
              <i class="el-icon-close" style="font-size: 18px"></i>
            </div>
          </div>
          <div class="container-content background-color-grey padding-10">
            <div class="background-color-white padding-10">
              <el-form :model="addExam" :rules="addExamRule" ref="addExam" label-width="80px">
                <el-form-item label="考试名称" prop="name">
                  <el-input v-model="addExam.name" placeholder="考试名称"></el-input>
                </el-form-item>
                <el-form-item label="总分" prop="totalScore">
                  <el-input v-model="addExam.totalScore" placeholder="总分"></el-input>
                </el-form-item>
                <el-form-item label="合格分" prop="passScore">
                  <el-input disabled v-model="addExam.passScore" placeholder="合格分"></el-input>
                </el-form-item>
                <!-- <el-form-item label="出题模式" prop="isRandom">
                  <el-radio-group v-model="addExam.isRandom">
                    <el-radio :label="0">手动</el-radio>
                    <el-radio :label="1">导入</el-radio>
                  </el-radio-group>
                </el-form-item> -->
                <!-- 如果是手动出题，显示添加试题按钮，如果是导入，显示上传课件和下载模板按钮 -->
                <el-form-item label="试题设置" prop="examItemList" v-if="addExam.isRandom === 0">
                  <div>
                    <el-button type="primary" size="mini" @click="addExamItemOpen()">添加试题</el-button>
                    <span
                      class="margin-left-sm cursor-pointer text-primary">试题数量({{ addExam.examItemList.length }})</span>
                  </div>
                  <template v-if="addExam.examItemList && addExam.examItemList.length > 0">
                    <el-card v-for="(item, index) in addExam.examItemList" class="box-card addExamCard margin-top-sm"
                      :key="item.name">
                      <div>
                        <div style="min-height: 40px;line-height: 30px"
                          class="flex justify-between align-center border-bottom padding-lr-sm">
                          <div class="flex-1 text-16">{{index+1}}、{{ item.name }}</div>
                          <div>
                            <el-button type="text" size="mini" v-if="index !== 0"
                              @click="handleAddExamItemUp(index)">上移</el-button>
                            <el-button type="text" size="mini" v-if="index !== addExam.examItemList.length - 1"
                              @click="handleAddExamItemDown(index)">下移</el-button>
                            <el-button type="text" size="mini" @click="handleAddExamItemDelete(index)">删除</el-button>
                          </div>

                        </div>
                        <div class="flex-column justify-between padding-lr-lg">
                          <div v-if="item.a" class="padding-lr-lg margin-tb-sm" :class="item.ans.indexOf('a')!=-1 ? 'bg-green text-white' : ''">
                            A.&nbsp;{{ item.a }}
                          </div>
                          <div v-if="item.b" class="padding-lr-lg  margin-tb-sm" :class="item.ans.indexOf('b')!=-1 ? 'bg-green text-white' : ''">
                            B.&nbsp;{{ item.b }}
                          </div>
                          <div v-if="item.c" class="padding-lr-lg  margin-tb-sm" :class="item.ans.indexOf('c')!=-1 ? 'bg-green text-white' : ''">
                            C.&nbsp;{{ item.c }}
                          </div>
                          <div v-if="item.d" class="padding-lr-lg  margin-tb-sm" :class="item.ans.indexOf('d')!=-1 ? 'bg-green text-white' : ''">
                            D.&nbsp;{{ item.d }}
                          </div>
                        </div>

                      </div>
                    </el-card>
                  </template>

                </el-form-item>


              </el-form>

            </div>
          </div>
          <div class="flex justify-center padding-10">
            <el-button type="primary" @click="addExamSubmit">保存</el-button>
          </div>
        </div>

      </el-drawer>
</template>
<script>
import examItemAddOrUpdate from './exam-item-add-or-update'
export default {
  data() {
    return {
        addOrUpdateVisible:false,

        addExam:{
            manageId: '',
            manageName: '',
            name: '',
            isRandom: 0,
            totalNum: '',
            totalScore: 100,
            passScore: 60,
            sort: 99,
            examItemList: [],
      },
        configForm:{},
        addExamDrawer:false,
        addExamRule: {
        name: [
          { required: true, message: '考试名称不能为空', trigger: 'blur' }
        ],
        totalScore: [
          { required: true, message: '总分不能为空', trigger: 'blur' }
        ],
        passScore: [
          { required: true, message: '合格分不能为空', trigger: 'blur' }
        ],
        examItemList: [
          { required: true, message: '请添加考试题目', trigger: 'blur' }
        ]
      },

    }
  },
  components: { examItemAddOrUpdate },
  watch: {
    "addExam.totalScore" (val) {
      if(val){
        this.addExam.passScore = Number((val * (this.configForm.exam_pass_scroe_ratio?(Number(this.configForm.exam_pass_scroe_ratio)/100):0.6) ).toFixed(2))
      }
    }
  },
  mounted() {
    console.log(document.body.clientHeight)
  },
  created() {
  },
  methods: {
    addExamSure(item){
        console.log(item)
        this.addExam.examItemList.push(item)
         //this.addExam.examItemList根据sort排序
      this.addExam.examItemList.sort((a, b) => {
        return a.sort - b.sort
      })

    },
    //获取全局配置
    async getConfig() {
      let res = await  this.$http({
        url: this.$http.adornUrl(`/sys/ysxhConfig/list`),
        method: 'get',
        params: this.$http.adornParams()
      })

      let data = res.data
      if (data && data.code === 0) {
          console.log(data)
          this.configForm = Object.assign({}, data.config.configMap)
          console.log(this.configForm)
        }
    },

    deleteAddExam(item, index) {
      console.log(item)
      //弹窗确认删除吗？
      this.$confirm('确定删除该考试吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.dataForm.examList.splice(index, 1)
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      })

    },

    initAddExam() {
      this.addExam = {
        manageId: '',
        manageName: '',
        name: '',
        isRandom: 0,
        totalNum: '',
        totalScore: 100,
        passScore: 60,
        sort: 1,
        examItemList: [],
      }
    },

    handleAddExamClose() {
      this.addExamDrawer = false;
      this.initAddExam();
      this.selectIndexExam = -1
    },

    addExamSubmit() {
      //名称，总分，合格分，排序必填，试题数量必须大于0
      if (!this.addExam.name) {
        this.$message.error('考试名称不能为空')
        return
      }
      if (!this.addExam.totalScore) {
        this.$message.error('总分不能为空')
        return
      }
      if (!this.addExam.passScore) {
        this.$message.error('合格分不能为空')
        return
      }
      if (!this.addExam.examItemList || this.addExam.examItemList.length <= 0) {
        this.$message.error('请添加考试题目')
        return
      }
      if (!this.addExam.sort&& this.addExam.sort !== 0 ) {
        this.$message.error('排序不能为空')
        return
      }
      let addParams = JSON.parse(JSON.stringify(this.addExam))
      console.log(addParams)
      //掉接口 /class/exam/update
        this.$http({
          url: this.$http.adornUrl(`/class/exam/update`),
          method: 'post',
          data: this.$http.adornData(addParams, false)
        }).then(({ data }) => {
          if (data && data.code === 0) {
            this.$message({
              message: '操作成功',
              type: 'success',
             duration: 1500,
            })
            this.$emit('refreshDataList')
            this.handleAddExamClose()
          }
        }).catch((err) => {
            console.log(err)
            this.$message({
              message: '操作失败',
              type: 'error',
              duration: 1500,
            })

        })
    },
    
    init(id) {
      this.addExam.id = id || 0
      this.addExamDrawer = true
      this.$nextTick(() => {
        this.$refs['addExam'].resetFields()
      })

      if (this.addExam.id) {
      this.$loading({
                lock: true,
                text: "加载中",
                background: "rgba(0, 0, 0, 0.5)",
            });
        this.$http({
          url: this.$http.adornUrl(`/class/exam/info/${this.addExam.id}`),
          method: 'get',
          params: this.$http.adornParams()
        }).then(({ data }) => {
          if (data && data.code === 0) {
            console.log(data)
            this.addExam = Object.assign({}, this.addExam, data.classExam)
            
          }
          this.$loading().close();
        }).catch((err) => {
          this.$loading().close();
        });
      }else{
        this.initAddExam();
      }
      this.getConfig();
    },

    addExamItemOpen(){
        this.addOrUpdateVisible = true
        this.$nextTick(() => {
            //获取排序
            let sort =(this.addExam&&this.addExam.examItemList&&this.addExam.examItemList.length>0)?this.addExam.examItemList[this.addExam.examItemList.length-1].sort+1:1
            this.$refs.addOrUpdate.init(sort,null)
        })
    },

    handleAddExamItemDelete(index) {
      this.addExam.examItemList.splice(index, 1)
    },
    handleAddExamItemUp(index) {
    // 深拷贝当前的 examItemList 数组
    let tempList = JSON.parse(JSON.stringify(this.addExam.examItemList));
    
    // 确保 index - 1 不会越界
    if (index <= 0) return;

    // 获取当前项和前一项
    let current = tempList[index];
    let previous = tempList[index - 1];

    // 交换位置
    tempList[index] = previous;
    tempList[index - 1] = current;

    // 交换 sort 属性
    let tempSort = current.sort;
    current.sort = previous.sort;
    previous.sort = tempSort;

    // 更新到原数组
    this.addExam.examItemList = JSON.parse(JSON.stringify(tempList));

    console.log(this.addExam.examItemList);
},

handleAddExamItemDown(index) {
    // 深拷贝当前的 examItemList 数组
    let tempList = JSON.parse(JSON.stringify(this.addExam.examItemList));

    // 确保 index + 1 不会越界
    if (index >= tempList.length - 1) return;

    // 获取当前项和后一项
    let current = tempList[index];
    let next = tempList[index + 1];

    // 交换位置
    tempList[index] = next;
    tempList[index + 1] = current;

    // 交换 sort 属性
    let tempSort = current.sort;
    current.sort = next.sort;
    next.sort = tempSort;

    // 更新到原数组
    this.addExam.examItemList = JSON.parse(JSON.stringify(tempList));

    console.log(this.addExam.examItemList);
},
  }
}
</script>
<style>
.right-container {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.container-header {
  height: 50px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px
}

.container-content {
  flex: 1;
}


.flex-container {
  display: flex;
  justify-content: space-between;
  /* 根据需要调整 */
}

.flex-item {
  flex: 1;
  /* 可以根据需要调整比例 */
  margin: 0 10px;
  /* 添加一些间距 */
}

.left-panel,
.right-panel {
  /* 在这里添加任何特定的样式，比如背景色、边框等 */
}

.el-tabs--border-card>.el-tabs__content {
  padding: 10px 0;
}

.el-radio__original {
  display: none;
}

.addExamCard>.el-card__body {
  padding: 0px;
}
</style>